package com.rabbiter.oes.controller;

import com.rabbiter.oes.service.BanksService;
import com.rabbiter.oes.service.FillQuestionService;
import com.rabbiter.oes.service.JudgeQuestionService;
import com.rabbiter.oes.service.MultiQuestionService;
import com.rabbiter.oes.entity.*;
import com.rabbiter.oes.util.ApiResultHandler;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("/questions")
public class QuestionImportController {

    @Autowired
    private MultiQuestionService multiQuestionService;  // 单选题

    @Autowired
    private FillQuestionService fillQuestionService;    // 多选题

    @Autowired
    private JudgeQuestionService judgeQuestionService;  // 判断题

    @Autowired
    private BanksService banksService;
    /**
     * 导入题库：支持单项选择题、多项选择题、判断题
     * 前端需上传 Excel 文件，并传入 subject（题库名称）
     */
    @PostMapping("/import")
    public ApiResult importQuestions(
            @RequestParam("file") MultipartFile file,
            @RequestParam("subject") String subject) {

        // 参数校验
        if (file.isEmpty()) {
            return ApiResultHandler.buildApiResult(400, "文件不能为空", null);
        }
        if (subject == null || subject.trim().isEmpty()) {
            return ApiResultHandler.buildApiResult(400, "题库名称不能为空", null);
        }
        subject = subject.trim();

        try {
            banksService.addIfNotExists(subject);
        } catch (Exception e) {
            e.printStackTrace();
            // 可选择继续导入题目，或中断
            // 这里选择继续导入，不影响主体功能
            System.err.println("保存题库名称失败: " + subject);
        }

        ImportResult result = new ImportResult();

        try (InputStream is = file.getInputStream();
             Workbook workbook = WorkbookFactory.create(is)) {

            Sheet sheet = workbook.getSheetAt(0); // 读取第一个 sheet
            for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                Row row = sheet.getRow(i);
                if (row == null) continue;

                try {
                    String stem = getCellValue(row.getCell(0));   // A列：题干
                    String type = getCellValue(row.getCell(1));   // B列：题型
                    String answer = getCellValue(row.getCell(2)); // C列：答案
                    String scoreStr = getCellValue(row.getCell(7)); // H列：分值（索引7）

                    // 必填字段校验
                    if (stem.isEmpty() || type.isEmpty() || answer.isEmpty()) {
                        result.addError(i + 1, "题干、题型或答案为空");
                        continue;
                    }

                    // 解析分值，支持默认值
                    Integer score = 1; // 默认分值
                    if (!scoreStr.isEmpty()) {
                        try {
                            score = Integer.parseInt(scoreStr.trim());
                            if (score <= 0) {
                                result.addError(i + 1, "分值必须大于0");
                                continue;
                            }
                        } catch (NumberFormatException e) {
                            result.addError(i + 1, "分值格式不正确: " + scoreStr);
                            continue;
                        }
                    }

                    switch (type.trim()) {
                        case "单项选择题":
                            MultiQuestion single = new MultiQuestion();
                            single.setQuestion(stem);
                            single.setAnswerA(getCellValue(row.getCell(3))); // D
                            single.setAnswerB(getCellValue(row.getCell(4))); // E
                            single.setAnswerC(getCellValue(row.getCell(5))); // F
                            single.setAnswerD(getCellValue(row.getCell(6))); // G
                            single.setRightAnswer(answer);
                            single.setSubject(subject);
                            single.setScore(score); // ✅ 设置分值

                            boolean singleSuccess = multiQuestionService.add(single) > 0;
                            if (singleSuccess) {
                                result.single++;
                            } else {
                                result.addError(i + 1, "单项选择题插入失败");
                            }
                            break;

                        case "多项选择题":
                            FillQuestion multiple = new FillQuestion();
                            multiple.setQuestion(stem);
                            multiple.setOptionA(getCellValue(row.getCell(3))); // D
                            multiple.setOptionB(getCellValue(row.getCell(4))); // E
                            multiple.setOptionC(getCellValue(row.getCell(5))); // F
                            multiple.setOptionD(getCellValue(row.getCell(6))); // G
                            multiple.setRightAnswer(answer);
                            multiple.setSubject(subject);
                            multiple.setScore(score); // ✅ 设置分值

                            boolean multipleSuccess = fillQuestionService.add(multiple) > 0;
                            if (multipleSuccess) {
                                result.multiple++;
                            } else {
                                result.addError(i + 1, "多项选择题插入失败");
                            }
                            break;

                        case "判断题":
                            JudgeQuestion judge = new JudgeQuestion();
                            judge.setQuestion(stem);
                            judge.setRightAnswer(answer);
                            judge.setOptionA(getCellValue(row.getCell(3))); // A选项
                            judge.setOptionB(getCellValue(row.getCell(4))); // B选项
                            judge.setSubject(subject);
                            judge.setScore(score); // ✅ 设置分值

                            boolean judgeSuccess = judgeQuestionService.add(judge) > 0;
                            if (judgeSuccess) {
                                result.judge++;
                            } else {
                                result.addError(i + 1, "判断题插入失败");
                            }
                            break;

                        default:
                            result.addError(i + 1, "不支持的题型: " + type);
                            break;
                    }
                } catch (Exception e) {
                    result.addError(i + 1, "解析异常: " + e.getMessage());
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            return ApiResultHandler.buildApiResult(500, "文件解析失败，请检查格式", null);
        }

        result.total = result.single + result.multiple + result.judge;
        return ApiResultHandler.buildApiResult(200, "导入完成", result);
    }

    /**
     * 工具方法：安全获取单元格字符串值
     */
    private String getCellValue(Cell cell) {
        if (cell == null) return "";
        switch (cell.getCellType()) {
            case STRING:
                return cell.getStringCellValue().trim();
            case NUMERIC:
                return String.valueOf((int) cell.getNumericCellValue()); // 去除 .0
            case BOOLEAN:
                return cell.getBooleanCellValue() ? "A" : "B";
            default:
                return "";
        }
    }

    // ================== 响应结果类 ==================

    /**
     * 导入结果统计
     */
    public static class ImportResult {
        public int single = 0;     // 单选题数量
        public int multiple = 0;   // 多选题数量
        public int judge = 0;      // 判断题数量
        public int total = 0;      // 总数
        public List<ImportError> errors = new ArrayList<>();

        public void addError(int row, String error) {
            errors.add(new ImportError(row, error));
        }
    }

    /**
     * 导入失败的行信息
     */
    public static class ImportError {
        private int row;
        private String error;

        public ImportError(int row, String error) {
            this.row = row;
            this.error = error;
        }

        public int getRow() { return row; }
        public void setRow(int row) { this.row = row; }
        public String getError() { return error; }
        public void setError(String error) { this.error = error; }
    }
}